package com.hmall.item.web;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.Item;
import com.hmall.item.service.IItemService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("item")
public class ItemController {

    @Autowired
    private IItemService itemService;


    @Autowired
    private RabbitTemplate rabbitTemplate;


    /**
     * 分页查询
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/list")
    public PageDTO<Item> list(@RequestParam("page") Integer pageNum, @RequestParam("size") Integer pageSize) {
        Page<Item> page = itemService.page(new Page<>(pageNum, pageSize));
        List<Item> records = page.getRecords();
        PageDTO<Item> pageDTO = new PageDTO<>();
        pageDTO.setTotal(page.getTotal());
        pageDTO.setList(records);
        return pageDTO;
    }


    /**
     * 获取商品详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id) {
        Item item = itemService.getById(id);
        return item;
    }


    /**
     * 新增商品
     *
     * @param item
     */
    @PostMapping()
    public void addItem(@RequestBody Item item) {
        itemService.save(item);
    }


    /**
     * 修改商品上架状态
     * @param id
     * @param status
     */
    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable Long id, @PathVariable Integer status) {
        LambdaUpdateWrapper<Item> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Item::getId, id)
                .set(Item::getStatus, status);
        itemService.update(null, wrapper);
        rabbitTemplate.convertAndSend("hmmall.fanout",null,status);
    }


    /**
     * 修改商品
     * @param item
     */
    @PutMapping()
    public void updateItem(@RequestBody Item item){
        itemService.updateById(item);
    }


    /**
     * 删除商品
     * @param id
     */
    @DeleteMapping("/{id}")
    public void deleteById(@PathVariable Long id){
        itemService.removeById(id);
    }


    /**
     * 扣减库存接口
     * @param itemId
     * @param num
     */
    @PutMapping("/stock/{itemId}/{num}")
    public void stockNum(@PathVariable Long itemId,@PathVariable Integer num){
        Item item = this.getById(itemId);
        item.setStock(item.getStock()-num);
        item.setSold(item.getSold()+num);
        itemService.update(item, Wrappers.<Item> lambdaUpdate().ge(Item::getStock,num));
    }

}